package com.framework;

import java.util.EnumSet;
import java.util.concurrent.Executor;

// 组件构建器
class ComponentBuilder {
    public static <T, R> EnhancedComponent<T, R> forComponent(Component<T, R> component) {
        return new EnhancedComponent<>(component);
    }

    static class EnhancedComponent<T, R> {
        private final Component<T, R> component;
        private final EnumSet<ComponentFeature> features = EnumSet.noneOf(ComponentFeature.class);
        private CacheManager cacheManager;
        private int cacheTtl = 300;
        private Executor executor;

        public EnhancedComponent(Component<T, R> component) {
            this.component = component;
        }

        public EnhancedComponent<T, R> withCaching(int ttlSeconds) {
            this.cacheManager = new CacheManager();
            this.cacheTtl = ttlSeconds;
            return this;
        }

        public EnhancedComponent<T, R> withLogging() {
            return this;
        }

        public EnhancedComponent<T, R> withAsync(Executor executor) {
            this.executor = executor;
            return this;
        }

        public Component<T, R> build() {
            Component<T, R> current = component;

            // 应用装饰器（按顺序很重要）
            if (cacheManager != null) {
                current = new CacheDecorator<>(current, cacheManager, cacheTtl, features);
            }

            if (features.contains(ComponentFeature.LOGGING)) {
                current = new LoggingDecorator<>(current, features);
            }

            if (executor != null) {
                current = new AsyncDecorator<>(current, executor, features);
            }

            return current;
        }
    }
}